<?php

namespace app\api\controller\log;
use app\api\controller\common\ApiBase;
use Think\Db;
class Contractlog extends ApiBase
{

    public function index()
    {
        if (request()->isPost()) {
        $post = input('post.');
        $page = isset($post['page']) && $post['page'] != '' ? $post['page'] : 1;
        $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
        $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
        $keyword = isset($post['keyword']) && $post['keyword'] != '' ? $post['keyword'] : null;
        $type = isset($post['type']) && $post['type'] != '' ? $post['type'] : null;
        $remember_id = isset($post['remember_id']) && $post['remember_id'] != '' ? $post['remember_id'] : null;
        $param=" and p.exhibition_id=$exhibition_id ";
        $tabName=$this->getTabName($exhibition_id);
        $tabName='crm_'.$tabName;
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键主键展会id']);
        }
        if (!empty($keyword)) {
            $param.=" and p.company_id in (select id from ".$tabName." where company_name like '%$keyword%') ";
        }

        if($remember_id){
            $param.=" and p.remember_id=".$remember_id;
        }

        if($type){
            $param.=" and p.contract_edit_type=".$type;
        }

        $sql2="select p.*,z.company_name,a.realname";
        $sql2.=" from crm_contract_log as p ";
        $sql2.=" left join ".$tabName." as z on z.id=p.company_id";
        $sql2.=" left join crm_admin as a on a.id=p.remember_id";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by p.id desc";
        $total=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>count($total)]]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }
    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
     }

}
